import EventDispatcher from "../cfw/event/EventDispatcher";
import RemoteProxy from "./proxy/RemoteProxy";
import { IRemoteProxyObserver } from "./proxy/IRemoteProxyObserver";
import { NetCode } from "./NetConfig";


export class NetClient extends EventDispatcher implements IRemoteProxyObserver {


    protected remoteProxy: RemoteProxy;

    constructor(proxy: RemoteProxy) {
        super();
        this.remoteProxy = proxy;
        this.remoteProxy.setObserver(this)
    }

    /**
     * 添加一次注册，之后不再需要
     * @param handler 
     * @param array 
     */
    addObservers(handler: Object, array: net.Observer[]) {
        for (let index = 0; index < array.length; index++) {
            let value = array[index];
            const protoId = value.protoId
            let func = value.callback;
            this.on(protoId, func, handler);
        }
    }

    removeObservers(handler: Object, array: net.Observer[]) {
        for (let index = 0; index < array.length; index++) {
            let value = array[index];
            const protoId = value.protoId
            let func = value.callback;
            this.off(protoId, func, handler);
        }
    }

    //统一返回到一个位置的方式。
    protected pushFunc: (func: net.PushData) => void;

    setPushFunc(func: (func: net.PushData) => void) {
        this.pushFunc = func;
    }

    sendData(data: net.SendData) {
        this.remoteProxy.onSendMessage(data)
    }

    onData(data: net.ResData) {
        this.emit(data.protoId, data.code, data.data);
    }



    onPush(data: net.PushData) {
        if (this.pushFunc) {
            this.pushFunc(data)
        }
        this.emit(data.protoId, NetCode.SUCCESS, data.data);
    }

}